package com.katze.boot.applet.asn1.adapter;

import com.katze.boot.applet.asn1.anlysis.ASN1Analysis;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1TaggedObject;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 每条数据长度固定
 */
public class ASN1FixedLengthAdapter implements BasicAdapter {

    private static ASN1FixedLengthAdapter adapter = null;
    private Path file;
    private Path output;
    private String filename;
    private int length;

    public ASN1FixedLengthAdapter() {}

    private void reset(Path file, String filename, int length, Path output) {
        this.file = file;
        this.filename = filename;
        this.length = length;
        this.output = output;
    }

    public static ASN1FixedLengthAdapter getInstance(Path file, String filename, int length, Path output){
        if (adapter == null) adapter = new ASN1FixedLengthAdapter();
        adapter.reset(file, filename, length, output);
        return adapter;
    }

    @Override
    public void run() {
        try (ASN1Analysis analysis = new ASN1Analysis(true, "@"); InputStream inputStream = Files.newInputStream(file)) {
            analysis.config(filename).storage(output);

            byte[] bs = new byte[length];//该话单为固定块大小
            ASN1Primitive primitive;
            while ((inputStream.read(bs)) >=0 ){
                try(ASN1InputStream bIn = new ASN1InputStream(bs)){
                    while ((primitive = bIn.readObject()) != null) {
                        if (bs.length == 2048){
                            // 电路与端局
//                            primitive = ((ASN1TaggedObject)primitive).getObject();
                            primitive = ((ASN1TaggedObject)primitive).getLoadedObject();
                        }
                        analysis.save(primitive);
                    }
                }catch (Exception e){
                    //遇FF出错丢弃
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
